<?php
/*
 * @Author: 乔
 * @Date: 2021-10-27 16:26:46
 * @LastEditTime: 2021-11-05 10:22:04
 * @LastEditors: 乔
 * @FilePath: \tp30\app\admin\controller\Upload.php
 */

namespace app\admin\controller;

use think\facade\Filesystem;
use think\facade\Request;

class Upload
{
    public static function upload($filed = 'img', $string = true, $dir = 'img')
    {
        //判断是否上传对应字段的图片
        try {
            $files = Request::file($filed);
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
            exit;
        }
        //没接到上传图片字段值
        if (!$files)   return [false, '没上传图片2'];
        //判断单图、多图
        if (is_array($files)) {
            //上传验证 fileSize最大字节 fileExt后缀  fileMime类型  image尺寸
            //try{
            //    validate(['imgs'=>'fileSize:1024000|fileExt:png,jpg'])->check(['imgs'=>$files]);
            //}catch (ValidateException $e){
            //    return $e->getMessage();
            //}
            //多图上传
            $path = [];
            foreach ($files as $file) {
                $img = Filesystem::putFile($dir, $file);
                $path[] = str_replace('\\', '/', $img);
            }
            if ($string) $path = implode(',', $path);
        } else {
            //上传验证 fileSize最大字节 fileExt后缀  fileMime类型  image尺寸
            //try{
            //    validate(['imgs'=>'fileSize:1024000|fileExt:png,jpg'])->check(['imgs'=>$files]);
            //    //validate(['imgs'=>'fileMime:image/jpeg'])->check(['imgs'=>$files]);
            //    //validate(['imgs'=>'image:300,300,jpg'])->check(['imgs'=>$files]);
            //}catch (ValidateException $e){
            //    return $e->getMessage();
            //}
            //单图上传
            $path = Filesystem::putFile($dir, $files);
            $path = str_replace('\\', '/', $path);
        }
        return [true, $path];
    }


    public static function removeImg($img)
    {
        if (is_array($img)) {
            foreach ($img as $v) {
                static::removeTwo($v);
            }
        } else {
            self::removeTwo($img);
        }
    }

    public static function removeTwo($img)
    {
        $unpath = str_replace('\\', '/', app()->getRootPath());
        $lin = $unpath . 'public/static/admin/linshi/' . $img;
        $zheng = $unpath . 'public/static/admin/' . $img;
        $dir = pathinfo($zheng)['dirname'] . "/";
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        rename($lin, $zheng);
    }
}
